package com.putao.album.fileupload;


import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.putao.album.ahibernate.dao.AhibernateDao;
import com.putao.album.ahibernate.table.TableUtils;
import com.putao.album.db.DatabaseHelper;
import com.putao.album.util.AppHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.Loger;
import com.putao.album.util.StringHelper;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUploadDBHelper {
    static private AhibernateDao<FileInfo> mDao;

    private static FileUploadDBHelper mInstance;

    public synchronized static FileUploadDBHelper getInstance() {
        if (mInstance == null) {
            SQLiteDatabase mDB;
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File file = new File(AppHelper.getAppDiskDir(), ".albun.db");
                try {
                    mDB = SQLiteDatabase.openOrCreateDatabase(file, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    mDB = DatabaseHelper.getInstance().getWritableDatabase();
                }
            } else {
                mDB = DatabaseHelper.getInstance().getWritableDatabase();
            }
            mInstance = new FileUploadDBHelper();
            mDao = new AhibernateDao<FileInfo>(mDB);
            try {
                TableUtils.createTable(mDB, true, FileInfo.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mInstance;
    }

    /**
     * 获取当前babyId的宝宝未上传成功的照片
     *
     * @param babyId
     * @return
     */
    public List<FileInfo> getUnfinishedFiles(String babyId) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("babyId", babyId);
        map.put("status", "0");
        List<FileInfo> items = queryList(map);
        //Loger.d("chen++++++getUnfinishedFiles():"+items.size());
        if (items != null && items.size() > 0) {
            //剔除已经不存在的文件
            for (int i = items.size() - 1; i >= 0; i--) {
                FileInfo item = items.get(i);
                File file = new File(item.getFilePath());
                if (!file.exists()) {
                    delete(item);
                    items.remove(item);
                }
            }
        }
        return items;
    }

    /**
     * 判断是否已经上传成功
     *
     * @param babyId
     * @param filePath
     * @return
     */
    public boolean isUploadSuccess(String babyId, String filePath) {
        File file = new File(filePath);

        if (StringHelper.isEmpty(babyId) || !file.exists()) {
            return false;
        }

        String headHash = CommonUtils.getFileHeadHash(file);
        Map<String, String> map = new HashMap<String, String>();
        map.put("babyId", babyId);
        map.put("headHash", headHash);
        List<FileInfo> items = queryList(map);
        if (items != null && items.size() > 0) {
            if (items.get(0).getStatus() > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public List<FileInfo> queryList(Map<String, String> where) {

        return mDao.queryList(FileInfo.class, where);
    }

    public List<FileInfo> queryList(Map<String, String> where, String orderColume) {
        return mDao.queryList(FileInfo.class, where, orderColume);
    }

    public List<FileInfo> queryList(FileInfo entity) {
        return mDao.queryList(entity);
    }

    public void update(FileInfo entity, Map<String, String> where) {
        mDao.update(entity, where);
    }

    public void update(FileInfo item) {
        long time = System.currentTimeMillis();
        Map<String, String> map = new HashMap<String, String>();
        map.put("babyId", item.getBabyId());
        map.put("filePath", item.getFilePath());

//        if (item.getHash() != null) {
//            map.put("hash", item.getHash());
//        }
        List<FileInfo> items = queryList(map);
//        Loger.d("chen+++update():" + (System.currentTimeMillis() - time));
        if ((items != null) && (items.size() > 0)) {
            update(item, map);
        } else {
            mDao.insert(item);
        }
//        Loger.d("chen+++update():" + (System.currentTimeMillis() - time));
    }

    public void delete(Map<String, String> where) {
        mDao.delete(FileInfo.class, where);
    }

    public void delete(FileInfo entity) {
        mDao.delete(entity);
    }

    public void truncate() {
        mDao.truncate(FileInfo.class);
    }

    public AhibernateDao<FileInfo> getDao() {
        return mDao;
    }
}
